// pages/my/my.js
const app=getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userinfo:{},
    token:'',
    wxUserInfo:'',
    modelStatus: false,
    showDialog: false,
    showClose: false,
    avatarUrl: '',
    nickName: '',
    temporaryToken: null,
    show:false,
    in_code: '',
    disabled: false
  },
  handleBindcode() {
    this.setData({
      show: true
    })
    wx.hideTabBar({
      animation: true,
    })
  },
  handleCancel() {
    this.setData({
      show: false
    })
    wx.showTabBar()
  },
  handleCodeInput(e) {
    this.setData({
      in_code: e.detail.value
    })
  },
  handleConfirm() {
    if(this.data.userinfo.is_one == 1) {
      wx.showToast({
        title: '已绑定邀请码',
        icon: 'none'
      })
      return
    }
    if(this.data.in_code == '') {
      wx.showToast({
        title: '未输入邀请码',
        icon: 'none'
      })
      return
    }
    const data ={
      token: this.data.temporaryToken || app.globalData.token,
      in_code: this.data.in_code,
      is_one: 1
    }
    app.requestJs('user/updateincode',{data}).then(res => {
      if(res.errcode == 0) {
        wx.showToast({
          title: res.message,
          icon: 'error'
        })
    }
    if(res.errcode == 1) {
        wx.showToast({
          title: res.message,
        })
        this.setData({
          show: false
      })
      wx.showTabBar()
    }
    })
  },
  setUserInfo () {
    this.setData({
      showDialog: true,
      showClose: true
    })
  },
  closeSubmit () {
    this.setData({
      showDialog: false
    })
  },
  setAvatarNickname (e) {
    let formData = e.detail.value
    if (!formData.headImgUrl) {
      wx.showToast({
        title: '请上传头像！',
        icon: 'none'
      })
      return
    }
    if (!formData.nickName) {
      wx.showToast({
        title: '请输入昵称！',
        icon: 'none'
      })
      return
    }
    let data = {
      token: this.data.temporaryToken || app.globalData.token,
      nickname: formData.nickName,
      
    }
    // if(this.data.userinfo.is_one == 1) {
    //   data = {...data,in_code:formData.in_code}
    // }
    app.requestJs("User/getnickname",{data: data, status1: true, message: false}).then(() => {
      this.setData({
        nickName: formData.nickName,
        showDialog: false,
        showClose: false
      })
    })
  },
  onChooseAvatar (e) {
    const { avatarUrl } = e.detail
    const data = {
      token: this.data.temporaryToken || app.globalData.token,
      head_pic: avatarUrl
    }
    app.requestJs("User/setinfo",{
      data: data,
      status1: true,
      message: false,
      upload: {
        name: 'head_pic'
      }
    }).then(({ data }) => {
      this.setData({
        avatarUrl: data.photo
      })
    })
  },
  bindgetuserinfo (e) {
    let _this=this;
    if(e.detail.errMsg=='getUserInfo:ok'){
      _this.setData({
        disabled:true,
        nickname:e.detail.userInfo.nickName
      })
      let userInfo = e.detail.userInfo;
      wx.setStorageSync("userInfo", userInfo);
      wx.login({
        success(res) {
          console.log(res);
          if (res.code) {
            _this.wxcode(res.code);
          } else {
            _this.setData({
              disabled:false
            })
            app.utilJs.toast({ title:res.errMsg});
          }
        }
      })
    }else{
      app.utilJs.toast({ title:'取消了授权'});
    }
  },
  wxcode:function(code){//微信登录获取token
    console.log(code);
    let _this=this;
    let scene=wx.getStorageSync('invitecode') || '';
    app.requestJs("User/wxauthorize",{data:{code,scene}}).then((res) => {
      console.log(res);
      if(res.errcode==1){
        app.utilJs.toast({ title: res.message, icon: 'success' });
        if (res.data.token){
          // _this.setUserName(res.data.token);
          // _this.setData({
          //   disabled:false,
          //   token:res.data.token
          // })
          // this.data.temporaryToken = res.data.token
          // 这里要先设置token,按原小程序逻辑在第一次登录时会走不到设置token的地方,然后到其他页面提示重新登录跳转到填写用户信息这里还是缺少tokens
          this.setData({
            temporaryToken: res.data.token,
            token: res.data.token
          })
          wx.setStorage({
            key: 'token',
            data: res.data.token
          })
          app.globalData.token = this.data.temporaryToken;
          this.getUserInfo(2)
        }
      }else{
        _this.setData({
          disabled:false
        })
        app.utilJs.toast({ title: res.message });
      }
    })
  },
  getUserInfo:function(type = 1){
    let data={token:app.globalData.token};
    if (type === 2) {
      data.token = this.data.temporaryToken
    }
    app.requestJs('user/index', {data}).then((res) => {
      if (res.errcode == 1) {
        let resData=res.data || {};
        if (!resData.nickname || !resData.photo) {
          this.setData({
            showDialog: true
          })
        } else {
          if (type === 2) {
            wx.setStorageSync("token", this.data.temporaryToken);//已注册
            app.globalData.token = this.data.temporaryToken;
          }
          this.setData({
            userinfo:resData,
            token:data.token,
            avatarUrl: resData.photo,
            nickName: resData.nickname,
            in_code: resData.in_code,
            disabled: resData.is_one == 2 ? false : true
          })
        }
      }else app.utilJs.toast({ title: res.message });
    })
  },
  showPicker () {
    this.setData({
      modelStatus: true
    })
  },
  closePicker () {
    this.setData({
      modelStatus: false
    })
  },
  callPhone:function(){
    if(app.globalData.token=='')app.userlogin();
    else{
      let phoneNumber=this.data.userinfo.kefutel || '';
      wx.makePhoneCall({
        phoneNumber //仅为示例，并非真实的电话号码
      })
    }
  },
  bindLink:function(e){
    if(app.globalData.token=='')app.userlogin();
    else{
      let url=e.currentTarget.dataset.url;
      wx.navigateTo({
        url
      })
    }
  },
  orderLink:function(e){
    // let index=e.currentTarget.dataset.index;
      // wx.navigateTo({
      //   url: '/pages/order/orderlist/orderlist?index='+index,
      // })
    if(app.globalData.token=='')app.userlogin();
    else {
      let index=e.currentTarget.dataset.index;
      wx.navigateTo({
        url: '/pages/order/orderlist/orderlist?index='+index,
      })
    }
  },
  orderAfterLink:function(){
    if(app.globalData.token=='')app.userlogin();
    else {
      wx.navigateTo({
        url: '/pages/order/refund_list/refund_list',
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // let wxUserInfo=wx.getStorageSync('userInfo');
    let token=wx.getStorageSync('token') || '';
    // console.log(wxUserInfo)
    // this.setData({
    //   wxUserInfo
    // })
    if(token=='')return
    else this.getUserInfo();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})